<template>
	<view class="container">
		<uni-notice-bar color="#2979FF" background-color="#EAF2FF" text="1.请先扫描组件辅材二维码获取辅材信息 2.选择报告类型 3.上传报告 4.点击提交" />
		<uni-card>
			<template #title>
				<uni-list>
					<uni-list-item clickable @click="scanCode" :show-extra-icon="true" :extra-icon="extraIcon"
						:rightText="$lang('辅材信息')" />
				</uni-list>
			</template>
			<uni-row>
				<uni-col :span="24">
					<text v-scan="scanCallBack">{{$lang('基地')}}：{{formData.factory}}</text>
				</uni-col>
			</uni-row>
			<uni-row>
				<uni-col :span="24">
					<text>{{$lang('物料编号')}}：{{formData.materialNo}}</text>
				</uni-col>
			</uni-row>
			<uni-row>
				<uni-col :span="24">
					<text>{{$lang('批次号')}}：{{formData.batchNo}}</text>
				</uni-col>
			</uni-row>
		</uni-card>
		<uni-section class="mt-[-10px] ml-10 mr-10 required" title="报告类型" type="line">
			<uni-data-select v-model="formData.reportType" :localdata="reportTypeList"></uni-data-select>
		</uni-section>
		<uni-section class="mt-5 ml-10 mr-10 pb-5 required" title="报告上传" type="line">
			<uni-file-picker class="ml-5" ref="fileRef" mode="grid" fileMediatype="image"
				:image-styles="imageStyles" limit="20" @select="fileSelect" @delete="fileDel">
				<template #default>
					<uni-icons type="plusempty" size="30" color="gray"></uni-icons>
				</template>
			</uni-file-picker>
		</uni-section>
		<button type="primary" class="m-10 mt-20 rounded-[90px] h-[40px] flex items-center justify-center"
			@click="submitForm">{{$lang('提交')}}</button>
	</view>
</template>

<script setup>
	import {
		uniScanCode
	} from '@/utils/common.js'
	import {
		saveReport,
		uploadAttachment
	} from '@/api/iqc/componentAuxiliaryRecord.js'
	const {
		proxy
	} = getCurrentInstance()

	const formData = reactive({
		factory: '',
		materialNo: '',
		batchNo: '',
		reportType: ''
	})

	const extraIcon = {
		color: '#ff0000',
		size: '25',
		type: 'scan'
	}
	const reportTypeList = ref([{
			value: "coaReport",
			text: "coa报告"
		},
		{
			value: "inspectionReport",
			text: "检验报告"
		}
	])
	const fileRef = ref(null)
	const pathValue = ref("")
	const files = ref([])
	const imageStyles = reactive({
		width: 64,
		height: 64,
		border: {
			color: "#877c7c",
			width: 2,
			style: 'dashed',
			radius: '2px'
		}
	})

	function scanCallBack(binding, data) {
		let arr = data.split('_')
		var pattern = new RegExp("[^\u4e00-\u9fa5]")
		formData.factory = arr[0].replace(pattern, "") //过滤不可见非中文字符
		formData.materialNo = arr[1]
		formData.batchNo = arr[2]
	}

	function scanCode() {
		uniScanCode().then(res => {
			scanCallBack(null, res.result)
		})
	}

	function fileSelect(e) {
		e.tempFilePaths.forEach((it, index) => {
			files.value.push({
				name: `files${files.value.length}`,
				uri: it
			})
		})
	}

	function batchUpload() {
		let data = {
			businessType: "01",
			fileType: formData.reportType == "coaReport" ? "01" : "02",
			uniqueKey: `${formData.materialNo},${formData.batchNo}`
		}
		return uploadAttachment(files.value, data).then(res => {
			pathValue.value = res.data
		}).catch(err => {
			throw err
		})
	}
	//图片删除
	function fileDel(e) {
		const num = files.value.findIndex(v => v.uri === e.tempFilePath);
		files.value.splice(num, 1);
		files.value.forEach((it,index)=>{
			it.name=`files${index}`
		})
	}

	function submitForm() {
		if (!formData.factory || !formData.materialNo || !formData.batchNo) {
			proxy.$modal.msgError(proxy.$lang('请先扫码获取辅材信息'))
			return
		}
		if (!formData.reportType) {
			proxy.$modal.msgError(proxy.$lang('请选择报告类型'))
			return
		}
		if (files.value.length == 0) {
			proxy.$modal.msgError(proxy.$lang('请上传报告'))
			return
		}
		try {
			proxy.$modal.loading(proxy.$lang("上传中..."))
			batchUpload().then(res => {
				let data = {
					...formData
				}
				data[formData.reportType] = pathValue.value
				proxy.$modal.loading(proxy.$lang("提交中..."))
				saveReport(data).then(res => {
					proxy.$modal.msgSuccess(proxy.$lang('提交成功'))
					//清空数据
					resetForm()
				})
			}).catch(err => {
				const {
					message
				} = err;
				proxy.$modal.msgError(proxy.$lang("图片上传错误:{0}", [message || err]))
			}).finally(() => {
				proxy.$modal.closeLoading()
			})
		} catch (e) {
			proxy.$modal.closeLoading()
		}
	}

	function resetForm() {
		files.value = []
		Object.keys(formData).forEach(key => {
			formData[key] = '';
		});
	}
</script>

<style lang="scss">
	.required .uni-section-header::after {
		content: ' *';
		color: red;
	}

	.required {
		@apply relative;
	}

	.required .uni-section-header::after {
		@apply absolute text-red-500 ml-5;
	}

	::v-deep .uni-select {
		@apply h-45 !important;
	}
</style>